package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {


    @Override
    public List<Dict> getChildDataById(String id) {
        QueryWrapper<Dict> qw = new QueryWrapper<>();
        qw.eq("parent_id",id);
        List<Dict> list = this.list(qw);
        return list;
    }

    @Override
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> qw = new QueryWrapper<>();
        qw.eq("parent_id",id);
        List<Dict> dictList = this.list(qw);
        dictList.forEach(dict -> {
            QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
            dictQueryWrapper.eq("parent_id",dict.getId());
            dict.setHasChildren(this.list(dictQueryWrapper).size() > 0);
        });
        return dictList;
    }

    @Override
    public void exportData(HttpServletResponse response) {

        response.setContentType("application/vnd.ms-excel"); //指示响应内容的格式
        response.setCharacterEncoding("utf-8");

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = null;
        try {
            fileName = URLEncoder.encode("数据字典", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        // 指示响应内容以附件形式下载
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

        List<Dict> lists = this.list();
        List<DictEeVo> dictEeVos = new ArrayList<>();
        lists.forEach(list->{
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(list,dictEeVo);
            dictEeVos.add(dictEeVo);
        });
      /*  String string = JSON.toJSON(lists).toString();
        dictEeVos.add(JSON.parseObject(string, DictEeVo.class));*/
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet().doWrite(dictEeVos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void importData(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            List<DictEeVo> dictEeVos = EasyExcel.read(inputStream, DictEeVo.class, null).doReadAllSync();
            ArrayList<Dict> dicts = new ArrayList<>();
            dictEeVos.forEach(dictEeVo -> {
                Dict dict = new Dict();
                BeanUtils.copyProperties(dictEeVo,dict);
                dicts.add(dict);
            });
            this.saveBatch(dicts);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }


    @Override
    public String getNameByValue(String value) {
        QueryWrapper<Dict> qw = new QueryWrapper<>();
        qw.eq("value",value);
        Dict dict = baseMapper.selectOne(qw);
        return dict.getName();
    }

    @Override
    public String getNameByValueAndDictCode(String value, String dictCode) {

        if (!StringUtils.isEmpty(dictCode)){
            QueryWrapper<Dict> qw = new QueryWrapper<>();
            qw.eq("dict_code",dictCode);
            Dict selectOne = baseMapper.selectOne(qw);
            Long parentId = selectOne.getId();

            QueryWrapper<Dict> qw2 = new QueryWrapper<>();
            qw2.eq("value",value);
            qw2.eq("parent_id",parentId);
            Dict dict = baseMapper.selectOne(qw2);
            return dict.getName();
        }else{
            return this.getNameByValue(value);
        }

    }

    @Override
    public List<Dict> getDictByDictCode(String province) {
        QueryWrapper<Dict> qw = new QueryWrapper<>();
        qw.eq("dict_code",province);
        Dict dict = this.getOne(qw);

        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",dict.getId());
        List<Dict> list = this.list(queryWrapper);

        return list;
    }


}
